import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex) // vue的插件机制

// Vuex.Store 构造器选项
const store = new Vuex.Store({
	// 为了不和页面或组件的data中的造成混淆，state中的变量前面建议加上$符号
	state: {
		$token:'',
		// 用户信息
		$userInfo:undefined,
		$count: 1,
		//导航数据特点
		$catalogs: []
	},
	getters: {
		//只读，不可以修改
		getCatalogsByShow(state) {
			return state.$catalogs.filter(item => item.show_in_nav == 1)
		},
		getCatalogsByHidden() {

			return state.$catalogs.filter(item => item.show_in_nav == 0)
		}

	},
	mutations: {
		//修改用户信息
		//同步函数
		setUserinfo(state, userInfo) {
			state.$userInfo = userInfo
		},
		setToken(state,token){
			state.$token=token
		},
		increment(state) {
			state++
		},
		changeCount(state) {
			state.$count += 2;
		},
		setCatalogs(state, catalogs) {
			state.$catalogs = catalogs
			//修改时，要同时保存到缓存
			//uni.setStorageSync("catalogs",catalogs);
		},
		
		//代码优化
		changeAddCatalogByid(state, id) {
			let catalogs = state.$catalogs
			if (catalogs.length > 0) {
				catalogs.forEach(item => {
					if (item.id == id) {
						item.show_in_nav = 1
					}

				})

			}
			uni.setStorageSync("catalogs",catalogs);//数据更新

		},
		changeMinusCatalogByid(state, id) {
			let catalogs = state.$catalogs
			if (catalogs.length > 0) {
				catalogs.forEach(item => {
					if (item.id == id) {
						item.show_in_nav = 0
					}

				})
			}
			uni.setStorageSync("catalogs",catalogs);
		}
	},
	actions: {
		increateAync({
			commit
		}) {
			setTimeout(() => {
				commit('changeCount')
			}, 1000)

		}

	}

})

export default store
